import { Subject } from '@entity/Subject'
import { ResponseUtil } from '@helpers/ResponseUtil'
import { Controller, Get, Post } from '../metadata'
import { KoaContext } from '../server'

const SUBJECT_BODY = [
  'name:string',
  'cover:string',
  'studentCount:number',
  'schooltime:number',
  'yearPrice:number',
  'halfYearPrice:number',
  '?banners:string'
]

const UPDATE_SUBJECT_BODY = [
  '?name:string',
  '?cover:string',
  '?studentCount:number',
  '?schooltime:number',
  '?yearPrice:number',
  '?halfYearPrice:number',
  '?banners:string'
]

@Controller('/subject')
export class SubjectController {

  @Post('/create', { query: [], body: SUBJECT_BODY })
  public async createSubject(ctx: KoaContext<{}, Subject>) {
    const { mysql: { subjectService } } = ctx
    const { msg, code, id } = await subjectService.createSubject(ctx.request.body!)
    if (msg && code !== 0) {
      return ResponseUtil.fail(code, msg)
    }
    return ResponseUtil.success({ data: { id } })

  }

  @Get('/list', { query: ['?offset:number', '?count:number'], body: [] })
  public async getList(ctx: KoaContext<{ offset: number, count: number }>): Promise<ApiTypes.ApiBaseResult> {
    let { offset, count } = ctx.query
    if (!offset) {
      offset = 0
    }
    if (!count) {
      count = 10
    }
    const { mysql: { subjectService } } = ctx
    const { code, list, msg } = await subjectService.getSubjectList(offset, count)
    if (msg && code !== 0) {
      return ResponseUtil.fail(code, msg)
    }
    return ResponseUtil.success({ data: { list } })
  }

  @Get('/one', { query: ['id:number'], body: [] })
  public async getStudent(ctx: KoaContext<{ id: number }>): Promise<ApiTypes.ApiBaseResult> {
    let { id } = ctx.query
    const { mysql: { subjectService } } = ctx
    const { code, subject, msg } = await subjectService.getSubjectById(id)
    if (msg && code !== 0) {
      return ResponseUtil.fail(code, msg)
    }
    return ResponseUtil.success({ data: { subject } })
  }

  @Post('/update', { query: ['id:number'], body: UPDATE_SUBJECT_BODY })
  public async update(ctx: KoaContext<{ id: number }, Partial<Subject>>): Promise<ApiTypes.ApiBaseResult> {
    let { id } = ctx.query
    const { mysql: { subjectService } } = ctx
    const { code, msg } = await subjectService.updateSubjectInfo(id, ctx.request.body!)
    if (msg && code !== 0) {
      return ResponseUtil.fail(code, msg)
    }
    return ResponseUtil.success({})
  }

}
